<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>合同管理</el-breadcrumb-item>
      <el-breadcrumb-item>
        <span
          class="u-cursor"
          @click="goBack"
        >渠道合同</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{pageTitle}}渠道合同信息</el-breadcrumb-item>
    </el-breadcrumb>
    <Container class="u-pb60">
      <el-form
        class="m-form--detail"
        ref="contractForm"
        :model="contractData"
        :rules="contractRules"
        label-width="160px"
      >
        <ContainerTitle>合同基本信息</ContainerTitle>
        <el-form-item
          prop="__suitDepart"
          required
          label="合同适用部门："
        >
          <el-checkbox-group
            size="small"
            :disabled="pageAction === 'detail'"
            v-model="contractData.__suitDepart"
          >
            <el-checkbox :label="0">信息流</el-checkbox>
            <el-checkbox :label="1">商店分发</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          required
          v-if="['edit', 'detail'].indexOf(pageAction) !== -1"
          label="合同编号："
        >
          {{contractData.contractNo}}
        </el-form-item>
        <el-form-item
          prop="cooperatorName"
          required
          label="渠道主体："
        >
          <el-input
            :disabled="pageAction === 'detail'"
            v-model="contractData.cooperatorName"
            size="small"
            class="u-w350"
            placeholder="请输入渠道公司全称"
          />
          <el-radio
            :disabled="pageAction === 'detail'"
            class="u-ml10"
            size="small"
            v-model="contractData.ownerType"
            :label="0"
            border
          >甲方</el-radio>
        </el-form-item>
        <el-form-item
          prop="ownerBody"
          required
          label="我方主体："
        >
          <el-select
            :disabled="pageAction === 'detail'"
            v-model="contractData.ownerBody"
            class="u-w350"
            size="small"
            placeholder="请选择推广模式"
          >
            <el-option
              v-for="item in OUR_PART_OPTION"
              :key="item.key"
              :value="item.key"
              :label="item.value"
            />
          </el-select>
          <el-radio
            :disabled="pageAction === 'detail'"
            class="u-ml10"
            size="small"
            v-model="contractData.ownerType"
            :label="1"
            border
          >甲方</el-radio>
        </el-form-item>
        <el-form-item
          prop="__indate"
          required
          label="合同有效期："
        >
          <el-date-picker
            :disabled="pageAction === 'detail'"
            v-model="contractData.__indate"
            size="small"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同负责人：">
          <el-input
            :disabled="pageAction === 'detail'"
            v-model="contractData.shoulder"
            size="small"
            class="u-w350"
            placeholder="请输入合同负责人"
          />
        </el-form-item>
        <el-form-item label="合同扫描件：">
          <template v-if="pageAction === 'detail'">
            {{contractData.pdfName}}
            <el-link
              v-if="contractData.pdfPath"
              type="primary"
              :href="contractData.pdfPath"
              target="_blank"
            >下载</el-link>
          </template>
          <template v-else>
            <a
              v-show="contractData.pdfName"
              class="u-cursor u-mr10"
              :href="contractData.pdfPath"
            >{{contractData.pdfName}}</a>
            <el-upload
              style="display: inline;"
              class="u-w350"
              with-credentials
              :action="`${BASE_URL}/cpa/api/contract_new/upload`"
              :data="{
                id: contractData.id || ''
              }"
              :show-file-list="false"
              :on-success="pdfUpload"
              :before-upload="pdfBeforeUpload"
            >
              <el-tooltip
                effect="dark"
                content="格式PDF，大小5M以内"
                placement="top"
              >
                <el-button size="small">{{contractData.pdfName ? '重新上传' : '上传'}}</el-button>
              </el-tooltip>
            </el-upload>
          </template>
        </el-form-item>

        <ContainerTitle>合同其他信息</ContainerTitle>
        <el-form-item label="适用平台：">
          <el-select
            :disabled="pageAction === 'detail'"
            v-model="contractData.__suitPlatform"
            class="u-w350"
            filterable
            multiple
            size="small"
            placeholder="请选择适用平台"
          >
            <el-option
              v-for="item in platformOption"
              :key="item.key"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="适用产品：">
          <el-input
            :disabled="pageAction === 'detail'"
            autosize
            v-model="contractData.__suitProduct"
            type="textarea"
            size="small"
            class="u-w350"
            placeholder="请输入适用产品"
          />
        </el-form-item>
        <el-form-item label="推广模式：">
          <el-select
            :disabled="pageAction === 'detail'"
            v-model="contractData.__popMode"
            class="u-w350"
            multiple
            size="small"
            placeholder="请选择推广模式"
          >
            <el-option
              v-for="item in POPULARIZE_MODE_OPTION"
              :key="item.key"
              :value="item.key"
              :label="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户合同编号：">
          <el-input
            :disabled="pageAction === 'detail'"
            v-model="contractData.cooperateNo"
            class="u-w350"
            size="small"
            placeholder="请输入客户合同编号"
          />
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            :disabled="pageAction === 'detail'"
            autosize
            v-model="contractData.remark"
            class="u-w350"
            type="textarea"
            size="small"
            placeholder="请输入备注"
          />
        </el-form-item>
        <template v-if="pageAction === 'detail'">
          <el-form-item label="合同状态：">{{mapStatus(contractData.status)}}</el-form-item>
          <el-form-item label="合同创建时间：">{{contractData.createrTime}}</el-form-item>
          <el-form-item label="合同创建人：">{{contractData.creator}}</el-form-item>
          <el-form-item label="最后一次操作时间：">{{contractData.modifyTime}}</el-form-item>
          <el-form-item label="最后一次操作人：">{{contractData.modifier}}</el-form-item>
        </template>
      </el-form>
    </Container>
    <Affix :offset-bottom="0">
      <ButtonGroup
        isFixed
        align="right"
      >
        <el-button
          @click="goBack"
          size="small"
        >返回</el-button>
        <el-button
          v-if="pageAction === 'create'"
          size="small"
          type="primary"
          @click="fetchCreate"
        >确认</el-button>
        <el-button
          v-if="pageAction === 'edit'"
          size="small"
          type="primary"
          @click="fetchUpdate"
        >确认</el-button>
      </ButtonGroup>
    </Affix>
  </div>
</template>

<script>
import ContainerTitle from "@/components/container-title";
import Container from "@/components/container";
import Affix from "@/components/affix";
import ButtonGroup from "@/components/button-group";

import {
  OUR_PART_OPTION,
  POPULARIZE_MODE_OPTION,
  APPLICABLE_DEPT_OPTION,
  CUSTOMER_STATUS_OPTION
} from "@/assets/js/contract-option";
export default {
  components: {
    ContainerTitle,
    Container,
    Affix,
    ButtonGroup
  },
  data() {
    return {
      OUR_PART_OPTION,
      POPULARIZE_MODE_OPTION,
      APPLICABLE_DEPT_OPTION,
      CUSTOMER_STATUS_OPTION,

      BASE_URL: process.env.VUE_APP_BASE_URL,
      pageAction: this.$route.query.action,
      pdfLoading: null,
      isFirstMount: true,

      platformOption: [],
      platformOptionAssist: [],

      contractData: {
        __indate: [],
        __suitDepart: [],
        __suitPlatform: [],
        __popMode: [],
        __suitProduct: "",

        contractType: 2, // 1客户，2渠道
        cooperateNo: "",
        suitDepart: "",
        cooperatorName: "",
        ownerBody: "",
        ownerType: 0,
        startDate: "",
        endDate: "",
        shoulder: "",
        pdfName: "",
        pdfPath: "",
        suitPlatform: "",
        suitProduct: "",
        popMode: "",
        contractNo: "",
        remark: ""
      },
      contractRules: {
        __suitDepart: {
          validator: (rule, value, callback) => {
            if (!value.length) {
              callback(new Error("请选择合同适用部门"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        __indate: {
          validator: (rule, value, callback) => {
            if (!value || !value.length) {
              callback(new Error("请选择合同有效期"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        cooperatorName: {
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error("请输入渠道公司全称"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        ownerBody: {
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error("请选择推广模式"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        }
      }
    };
  },
  computed: {
    pageTitle() {
      return {
        create: "新增",
        edit: "编辑",
        detail: "查看"
      }[this.pageAction];
    },
    submitData() {
      let {
        __indate,
        __suitDepart,
        __suitPlatform,
        __popMode,
        __suitProduct,
        ...data
      } = this.contractData;
      return {
        ...data,
        suitDepart: __suitDepart.length >= 2 ? 2 : __suitDepart[0],
        suitPlatform: __suitPlatform.join(),
        popMode: __popMode.join(),
        suitProduct: __suitProduct.replace(/[,，]+/g, ","),
        startDate: __indate[0],
        endDate: __indate[1]
      };
    }
  },
  watch: {
    "contractData.__suitDepart"(v) {
      this.platformOption = this.platformOptionAssist.filter(
        item => v.indexOf(item.type) !== -1
      );
      // 新建、编辑（除第一次以外）
      if (
        this.pageAction === "create" ||
        (this.pageAction === "edit" && !this.isFirstMount)
      ) {
        this.contractData.__suitPlatform = [];
      }
      this.isFirstMount = false;
    }
  },
  methods: {
    // 适用平台
    fetchPlatformOption() {
      return this.$http({
        method: "get",
        url: "/cpa/api/contract_new/platformlist",
        params: {
          type: 2
        }
      }).then(res => {
        this.platformOptionAssist = res.data.list || [];
      });
    },
    // 新增
    fetchCreate() {
      this.$refs["contractForm"].validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/cpa/api/contract_new/create",
            data: this.submitData
          }).then(res => {
            if (res.data.status === 1) {
              this.$message({
                type: "success",
                message: "新增成功"
              });
            }
            setTimeout(() => {
              this.goBack();
            }, 1000);
          });
        }
      });
    },
    // 更新
    fetchUpdate() {
      this.$refs["contractForm"].validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/cpa/api/contract_new/update",
            data: this.submitData
          }).then(res => {
            if (res.data.status === 1) {
              this.$message({
                type: "success",
                message: "更新成功"
              });
            }
            setTimeout(() => {
              this.goBack();
            }, 1000);
          });
        }
      });
    },
    // 详情
    fetchDetail() {
      this.$http({
        method: "get",
        url: "/cpa/api/contract_new/findone",
        params: {
          id: this.$route.query.id
        }
      }).then(res => {
        let data = res.data.item;
        this.contractData = {
          ...data,
          __suitDepart: data.suitDepart >= 2 ? [0, 1] : [data.suitDepart],
          __suitPlatform: data.suitPlatform ? data.suitPlatform.split(",") : [],
          __suitProduct: data.suitProduct,
          __popMode: data.popMode ? data.popMode.split(",") : [],
          __indate: [data.startDate, data.endDate]
        };
      });
    },
    // 对应合同状态
    mapStatus(key) {
      if (typeof key === "undefined") return "";
      return CUSTOMER_STATUS_OPTION.filter(item => Number(item.key) === key)[0]
        .value;
    },
    // 操作提示
    uploadMessage(flag, success = "上传成功", error = "上传失败") {
      if (flag) {
        this.$message({
          type: "success",
          message: success
        });
      } else {
        this.$message({
          type: "error",
          message: error
        });
      }
    },
    // pdf上传
    pdfUpload(res) {
      if (res.status === 1) {
        this.contractData.pdfName = res.pdfName;
        this.contractData.pdfPath = res.pdfPath;
      } else {
        this.$message({
          type: "error",
          message: res.msg
        });
      }
      this.uploadMessage(res.status === 1);
      this.pdfLoading.close();
    },
    pdfBeforeUpload(file) {
      const type = ["application/pdf"].indexOf(file.type) !== -1;
      const size = file.size / 1024 < 1024 * 5;
      if (!type) {
        this.$message.error("请上传pdf格式的文件");
        return false;
      }
      if (!size) {
        this.$message.error(`文件大小不能超过5MB`);
        return false;
      }
      this.pdfLoading = this.$loading({
        lock: true,
        text: "上传中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      return type && size;
    },
    // 返回
    goBack() {
      this.$router.replace({
        path: "/contract/contract-channel",
        query: this.$route.query.origin
      });
    }
  },
  created() {
    this.fetchPlatformOption().then(() => {
      // 编辑、查看获取详情
      if (["edit", "detail"].indexOf(this.pageAction) !== -1) {
        this.fetchDetail();
      }
    });
  }
};
</script>